#include "SList.h"

SListNode* BuyNode(SListDataType x)
{
	SListNode* ret = (SListNode*)malloc(sizeof(SListNode));
	if (ret == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	ret->data = x;
	ret->next = NULL;
	return ret;
}
void SListPrint(SListNode* phead)
{
	SListNode* pcur = phead;
	while (pcur)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("null\n");
}

void SListInit(SListNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	(*pphead)= NULL;
}


void SListDestroy(SListNode** pphead)
{
	assert(pphead);
	SListNode* pcur = *pphead;
	while (pcur)
	{
		SListNode* pnext = pcur->next;
		free(pcur);
		pcur = pnext;
	}
	*pphead = NULL;
}


void SListPushFront(SListNode** pphead, SListDataType x)
{
	assert(pphead);
	SListNode* pnext = *pphead;
	(*pphead) = BuyNode(x);
	(*pphead)->next = pnext;
	return;

}

void SListPopFront(SListNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SListNode* pnext = (*pphead)->next;
	free(*pphead);
	(*pphead) = pnext;
}


void SListPushBack(SListNode** pphead, SListDataType x)
{
	assert(pphead);
	if (*pphead == NULL)
	{
		*pphead = BuyNode(x);
		return;
	}
	else
	{
		SListNode* pcur = *pphead;
		while (pcur->next)
		{
			pcur = pcur->next;
		}
		pcur->next = BuyNode(x);
	}
	
}
void SListPopBack(SListNode** pphead)
{
	assert(pphead);
	assert(*pphead);

	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SListNode* pcur = *pphead;
	    SListNode * prev = NULL;
		while (pcur->next)
		{
			prev = pcur;
			pcur = pcur->next;
		}
		free(pcur);
		prev->next = NULL;
	}
}

SListNode* SListFind(SListNode* phead, SListDataType x)
{
	SListNode* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
			return pcur;
		pcur = pcur->next;
	}
	return NULL;
}

void SListInsert(SListNode** pphead, SListNode* pos, SListDataType x)
{
	if (pos == *pphead)
	{
		SListNode* pnext = (*pphead)->next;
		*pphead = BuyNode(x);
		(*pphead)->next = pnext;
		return;
	}
	else
	{
		SListNode* pcur = *pphead;
		SListNode* prev = NULL;
		while (pcur != pos)
		{
			prev = pcur;
			pcur = pcur->next;
		}
		prev->next = BuyNode(x);
		prev->next->next = pcur;
	}


}
void SListErase(SListNode** pphead, SListNode* pos)
{
	if (pos == *pphead)
	{
		SListNode* pnext = (*pphead)->next;
		free(*pphead);
		*pphead = pnext;
		return;

	}
	else 
	{
		SListNode* pcur = *pphead;
		SListNode* prev = NULL;
		while (pcur != pos)
		{
			prev = pcur;
			pcur = pcur->next;
		}
		prev->next = pcur->next;
		free(pcur);
	}
}

void SListInsertAfter(SListNode** phead, SListNode* pos, SListDataType x)
{
    SListNode* tmp =  pos->next;
	pos->next = BuyNode(x);
	pos->next->next = tmp;
}